package com.demo.order.controller;

import cn.hutool.core.bean.BeanUtil;
import com.demo.common.entity.ShoppingCart;
import com.demo.common.response.Result;
import com.demo.order.service.ShoppingCartService;
import com.goods.feign.client.GoodsServiceClient;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import jakarta.validation.Valid;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Positive;
import java.util.Map;

/**
 * 购物车控制器
 * 提供购物车的增删改查接口，支持与商品服务的联合查询
 *
 * @author demo
 * @since 1.0.0
 */
@RestController
@RequestMapping("/order")
@CrossOrigin(origins = "*", maxAge = 3600) // 允许跨域，生产环境应该限制具体域名
@Validated
@Slf4j
public class ShoppingCartController {

    private final ShoppingCartService shoppingCartService;
    private final GoodsServiceClient goodsServiceClient;

    /**
     * 构造函数注入依赖
     * 
     * @param shoppingCartService 购物车服务
     * @param goodsServiceClient 商品服务客户端
     */
    @Autowired
    public ShoppingCartController(ShoppingCartService shoppingCartService, GoodsServiceClient goodsServiceClient) {
        this.shoppingCartService = shoppingCartService;
        this.goodsServiceClient = goodsServiceClient;
    }

    /**
     * 获取所有购物车记录
     * 
     * @return 购物车列表
     */
    @GetMapping
    public Result<?> getAll() {
        try {
            log.info("开始获取所有购物车记录");
            return Result.success(shoppingCartService.list());
        } catch (Exception e) {
            log.error("获取购物车列表失败: {}", e.getMessage(), e);
            return Result.error("获取购物车列表失败");
        }
    }

    /**
     * 根据ID获取购物车详情（包含商品信息）
     * 通过Feign客户端调用商品服务获取商品详细信息
     * 
     * @param id 购物车ID
     * @return 购物车详情（包含商品信息）
     */
    @GetMapping("/{id}")
    public Result<?> getById(@PathVariable("id") @NotNull @Positive Long id) {
        try {
            log.info("开始获取购物车详情，购物车ID: {}", id);
            
            // 获取购物车信息
            ShoppingCart shoppingCart = shoppingCartService.getById(id);
            if (shoppingCart == null) {
                log.warn("购物车不存在，购物车ID: {}", id);
                return Result.error("购物车不存在");
            }
            
            log.info("购物车信息: {}", shoppingCart);
            
            // 将购物车信息转换为Map
            Map<String, Object> result = BeanUtil.beanToMap(shoppingCart, true, true);
            
            // 通过Feign客户端获取商品信息
            try {
                Result<?> goodsResult = goodsServiceClient.getById(shoppingCart.getProductId());
                if (goodsResult != null && goodsResult.getCode() == 200 && goodsResult.getData() != null) {
                    Map<String, Object> goodsInfo = BeanUtil.beanToMap(goodsResult.getData(), true, true);
                    result.putAll(goodsInfo);
                    log.info("成功获取商品信息，商品ID: {}", shoppingCart.getProductId());
                } else {
                    log.warn("获取商品信息失败，商品ID: {}", shoppingCart.getProductId());
                    result.put("goodsError", "商品信息获取失败");
                }
            } catch (Exception e) {
                log.error("调用商品服务失败，商品ID: {}, 错误信息: {}", shoppingCart.getProductId(), e.getMessage());
                result.put("goodsError", "商品服务暂不可用");
            }
            
            return Result.success(result);
            
        } catch (Exception e) {
            log.error("获取购物车详情失败，购物车ID: {}, 错误信息: {}", id, e.getMessage(), e);
            return Result.error("获取购物车详情失败");
        }
    }

    /**
     * 新增购物车记录
     * 
     * @param shoppingCart 购物车信息
     * @return 操作结果
     */
    @PostMapping
    public Result<?> add(@RequestBody @Valid ShoppingCart shoppingCart) {
        try {
            log.info("开始新增购物车记录，商品ID: {}", shoppingCart.getProductId());
            boolean success = shoppingCartService.save(shoppingCart);
            if (success) {
                log.info("购物车记录新增成功，购物车ID: {}", shoppingCart.getId());
                return Result.success(shoppingCart);
            } else {
                log.warn("购物车记录新增失败");
                return Result.error("购物车记录新增失败");
            }
        } catch (Exception e) {
            log.error("购物车记录新增失败，错误信息: {}", e.getMessage(), e);
            return Result.error("购物车记录新增失败");
        }
    }

    /**
     * 更新购物车记录
     * 
     * @param shoppingCart 购物车信息
     * @return 操作结果
     */
    @PutMapping
    public Result<?> update(@RequestBody @Valid ShoppingCart shoppingCart) {
        try {
            log.info("开始更新购物车记录，购物车ID: {}", shoppingCart.getId());
            boolean success = shoppingCartService.updateById(shoppingCart);
            if (success) {
                log.info("购物车记录更新成功，购物车ID: {}", shoppingCart.getId());
                return Result.success("购物车记录更新成功");
            } else {
                log.warn("购物车记录更新失败，购物车ID: {}", shoppingCart.getId());
                return Result.error("购物车记录更新失败");
            }
        } catch (Exception e) {
            log.error("购物车记录更新失败，购物车ID: {}, 错误信息: {}", shoppingCart.getId(), e.getMessage(), e);
            return Result.error("购物车记录更新失败");
        }
    }

    /**
     * 删除购物车记录
     * 
     * @param id 购物车ID
     * @return 操作结果
     */
    @DeleteMapping("/{id}")
    public Result<?> delete(@PathVariable("id") @NotNull @Positive Long id) {
        try {
            log.info("开始删除购物车记录，购物车ID: {}", id);
            boolean success = shoppingCartService.removeById(id);
            if (success) {
                log.info("购物车记录删除成功，购物车ID: {}", id);
                return Result.success("购物车记录删除成功");
            } else {
                log.warn("购物车记录删除失败，购物车ID: {}", id);
                return Result.error("购物车记录删除失败");
            }
        } catch (Exception e) {
            log.error("购物车记录删除失败，购物车ID: {}, 错误信息: {}", id, e.getMessage(), e);
            return Result.error("购物车记录删除失败");
        }
    }
}
